package com.test.rabbitmq;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.Optional;

public class RabbitMQUtil {

    public static final String DEF_IP = "192.168.85.121";

    public static final Integer DEF_PORT = 5672;

    public static final String DEF_HOST = "testhost";

    public static Connection getConn(String ip, Integer prot, String host, String name, String pwd) throws Exception {
        //定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务地址
        factory.setHost(Optional.ofNullable(ip).orElse(DEF_IP));
        //端口
        factory.setPort(Optional.ofNullable(prot).orElse(DEF_PORT));
        //设置账号信息，用户名、密码、vhost
        factory.setVirtualHost(Optional.ofNullable(host).orElse(DEF_HOST));
        factory.setUsername(name);
        factory.setPassword(pwd);
        // 通过工程获取连接
        Connection conn = factory.newConnection();
        return conn;
    }

    public static Connection getConn(String host, String name, String pwd) throws Exception {
        return getConn(null, null, host, name, pwd);
    }

    public static Connection getConn(String name, String pwd) throws Exception {
        return getConn(null, null, null, name, pwd);
    }
}
